package com.cnebula.uas.sso.service.impl;

import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cnebula.uas.sso.model.IdpAuthCenter;
import com.cnebula.uas.sso.service.IdpAuthCenterService;
import com.cnebula.uas.sso.service.IdpLoginValidService;

@Service
public class IdpLoginValidServiceImpl implements IdpLoginValidService {

	@Autowired
	IdpAuthCenterService idpAuthCenterService;

	@Override
	public String valid(String idpCode, String artifact) throws Exception {
		
		IdpAuthCenter idpAuthCenter = idpAuthCenterService.getIdpAuthCenter(idpCode);

		String loginValidURL = idpAuthCenter.loginValidURL;

		URIBuilder builder = new URIBuilder(loginValidURL);
		builder.setParameter("artifact", artifact);

		URI url = builder.build();
		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
		CloseableHttpResponse res = client.execute(httpGet);
		HttpEntity entity = res.getEntity();

		String content = EntityUtils.toString(entity, "utf-8");
		res.close();

		return content;
	}

}
